﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Borg.Framework
{
    public class PlugAction : Action
    {
        public PlugAction(SlotInfo slot)
            : base(slot, null)
        { }

        public PlugAction(SlotInfo slot, QualifyDelegate qualify)
            : base(slot, qualify)
        { }

        public PlugAction(SlotInfo slot, PlugTypeInfo plugType)
            : base(slot, null)
        {
            PlugType = plugType;
        }

        public PlugAction(SlotInfo slot, string param, object value)
            : base(slot, param, value)
        { }

        public override void Do(object s, EventArgs args)
        {
            var extTypes = new List<ExtensionTypeInfo>();

            if (PlugType != null)
                extTypes.Add(PlugType.ExtensionTypeInfo);
            else
            {
                foreach (var plugType in Slot.RegisteredPlugTypeInfos.
                    Where(plugType => (Qualify == null) || Qualify(plugType)))
                {
                    extTypes.Add(plugType.ExtensionTypeInfo);

                    if (!Slot.SlotTypeInfo.Multiple)
                        break;
                }
            }

            foreach (var extType in extTypes)
                if (Slot.Unique)
                    extType.CreateUniqueExtension().PlugPlugs(Slot.ExtensionInfo);
                else
                    extType.GetSharedExtension(true).PlugPlugs();
        }

        public PlugTypeInfo PlugType { get; private set; }
    }
}

